import React, { useEffect, useRef, useState } from 'react'
import { Button, Card, DatePicker, Drawer, Form, Input, message, Modal, Select, Tag } from 'antd';
import styles from './style.less'
import { getTeacherCourse, getTeacherTest, getStudentList, deleteStudent, getYearStudent, addYearStudent, changeCourse, deleteCourse, addCourse, deleteTests, getAnswerTest, getTestResult, addTests, addTestQuestions } from './service'
import ProTable from '@ant-design/pro-table';
import MPageContainer from '@/components/MPageContainer';
import { PlusOutlined } from '@ant-design/icons';
import qs from 'qs'
import moment from 'moment';
import Judge from '@/pages/student/course/components/Judge';
import Program from '@/pages/student/course/components/Program';
import Choice from '@/pages/student/course/components/Choice';
import Blanks from '@/pages/student/course/components/Blanks';

const Center: React.FC = () => {

    const [courseInfo, setCourseInfo] = useState();
    const [tableData, setTableData] = useState({});
    const [studentList, setStudentList] = useState([]);
    const [yearList, setYearList] = useState([])
    const [studentListVisvible, setStudentListVisvible] = useState(false)
    const [courseId, setCourseId] = useState<any>()
    const [addVisvible, setAddVisvible] = useState(false)
    const [changeCourseVisvible, setChangeCourseVisvible] = useState(false)
    const [startTime, setStartTime] = useState<any>()
    const [endTime, setEndTime] = useState<any>()
    const [add, setAdd] = useState(false)
    const [visible, setVisible] = useState(false)
    const [testType, setTestType] = useState()
    const [questions, setQuestions] = useState<any>()
    const [testId, setTestId] = useState()
    const [addTestVisvible, setAddTestVisvible] = useState(false)
    const [startTestTime, setTestStartTime] = useState<any>()
    const [endTestTime, setTestEndTime] = useState<any>()
    const [addQuestionVisvible, setAddQuestionVisvible] = useState(false)
    const [q1, setQ1] = useState<any>()
    const [q2, setQ2] = useState<any>()
    const [q3, setQ3] = useState<any>()
    const [q4, setQ4] = useState<any>()
    const [questionAddIds, setQuestionAddIds] = useState({})
    const [studentScoreVisvible, setStudentScoreVisvible] = useState(false)
    const [studentScoreList, setStudentScoreList] = useState([])

    // const [idList, setIdList] = useState([])


    const info: any = localStorage.getItem('info')
    const showInfo = JSON.parse(info);
    const teacherId = showInfo.teacherId;
    const drawerRef = useRef<Input | null>(null);

    const { Item } = Form;
    const { Option } = Select;

    const [yearForm] = Form.useForm();
    const [changeCourseForm] = Form.useForm();
    const [addTestForm] = Form.useForm()

    const formLayout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
    };

    const getCourse = async () => {
        const res = await getTeacherCourse(teacherId)
        setCourseInfo(res.data)
    }

    useEffect(() => {
        getCourse()
    }, [])

    const enterTest = async (record: any) => {
        setTestType(record.type)
        setTestId(record.testId)
        const res = await getAnswerTest(record.testId);
        if (res.code === 200) {
            setQuestions(res.data)
            setVisible(true)
        }
    }

    // 删除测验
    const deleteTest = async (record: any) => {
        const obj = {
            testId: record.testId
        }

        const res = await deleteTests(qs.stringify(obj))
        if (res.code === 200) {
            message.success('删除成功')
            const ress = await getTeacherTest(record.courseId)
            setTableData({
                ...tableData,
                [record.courseId]: ress.data
            })
        }
    }

    // 查看成绩
    const checkResult = async (record: any) => {
        setStudentScoreVisvible(true)
        const res = await getTestResult(record.testId);
        if (res.code === 200) {
            setStudentScoreList(res.data)
        }
        console.log(res, 'res');
    }

    useEffect(() => {
        console.log(studentScoreList, 'studentScoreList');
    })

    const addTest = async (id: any) => {
        setAddTestVisvible(true)
        setCourseId(id)
    }

    const onExpand = (expanded: boolean, record: any) => {
        const getTestList = async () => {
            const res = await getTeacherTest(record.courseId)
            setTableData({
                ...tableData,
                [record.courseId]: res.data
            })
        }
        if (expanded) {
            getTestList()
        }
    }

    const expandedRowRender = (record: any) => {
        return (
            <ProTable
                headerTitle={'测验列表'}
                columns={[
                    {
                        title: '类型',
                        dataIndex: 'type',
                        render: (text: any, record: any) => {
                            return <Tag color={text === 1 ? 'yellow' : 'green'}>{text === 1 ? '测验' : '考试'}</Tag>
                        },
                    },
                    { title: '测验名称', dataIndex: 'testName' },
                    { title: '开始时间', dataIndex: 'startTime' },
                    { title: '结束时间', dataIndex: 'endTime' },
                    {
                        title: '持续时间',
                        dataIndex: 'durationTime',
                        render: (text: any, record: any) => {
                            const start: any = new Date(record.startTime)
                            const end: any = new Date(record.endTime)
                            const time = Math.floor((end - start) / 1000 / 60)
                            return `${time} 分钟`
                        },
                    },
                    {
                        title: '操作',
                        dataIndex: 'operation',
                        render: (_: any, record: any) => {
                            return <>
                                <Tag color={'blue'} onClick={() => { enterTest(record) }} className={styles.classTag}>进入测验</Tag>
                                <Tag color={'red'} onClick={() => { deleteTest(record) }} className={styles.classTag}>删除测验</Tag>
                                <Tag color={'yellow'} onClick={() => { checkResult(record) }} className={styles.classTag}>查看成绩</Tag>
                            </>
                        }
                    },
                ]}
                key='testId'
                search={false}
                options={false}
                dataSource={tableData[record.courseId]}
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { addTest(record.courseId) }}>
                        添加测验
                    </Button>
                ]}
                pagination={{
                    showQuickJumper: true,
                }}
            />
        );
    };

    // 学生列表
    const getStudentLists = async (record: any) => {
        setStudentListVisvible(true)
        const res = await getStudentList(record.courseId);
        if (res.code === 200) {
            setStudentList(res.data)
            setCourseId(record.courseId)
        }
    }

    const handlestudentListCancel = () => {
        setStudentListVisvible(false)
        setStudentScoreList([])
    }

    // 删除学生
    const deleteStudentLists = async (studentId: any) => {
        const obj = {
            courseId: courseId,
            studentIds: studentId
        }
        const res = await deleteStudent(qs.stringify(obj))
        console.log(res, 'pppp');
        if (res.code === 200) {
            message.success('删除成功')
            const res = await getStudentList(courseId);
            if (res.code === 200) {
                setStudentList(res.data)
            }
        }
    }

    // 添加学生
    const addStudentLists = async () => {
        setAddVisvible(true)
    }

    const handleAddStudentCancel = () => {
        setAddVisvible(false)
    }

    // 根据年级列表添加学生
    const addYearLists = async (id: any) => {
        const obj = {
            courseId: courseId,
            studentIds: id
        }
        const res = await addYearStudent(qs.stringify(obj))
        if (res.code === 200) {
            message.success('添加成功')
            const res = await getStudentList(courseId);
            if (res.code === 200) {
                setStudentList(res.data)
            }
        }
    }

    // 修改课程
    const changeCourseList = async (record: any) => {
        setCourseId(record.courseId)
        setChangeCourseVisvible(true)
        setAdd(false)
    }

    const handleChangeCourseOk = async () => {
        const obj = await changeCourseForm.validateFields();
        const value = {
            ...obj,
            courseId: courseId,
            startTime: startTime,
            endTime: endTime
        }
        let res;
        if (add === true) {
            res = await addCourse(qs.stringify(value))
        } else {
            res = await changeCourse(qs.stringify(value))
        }
        if (res.code === 200) {
            message.success(add === true ? '添加成功' : '修改成功')
            getCourse()
        }
        setChangeCourseVisvible(false)
    }

    const handleChangeCourseCancel = () => {
        setChangeCourseVisvible(false)
    }

    // 新建课程
    const addCourseList = async () => {
        setChangeCourseVisvible(true)
        setAdd(true)
    }

    // 删除课程
    const deleteCourseList = async (record: any) => {
        const res = await deleteCourse(record.courseId)
        console.log(res, 'resresresjjjjjj');
        if (res.code === 200) {
            message.success('删除成功')
            getCourse()
        }
    }

    const columns = [
        {
            title: '课程名字',
            dataIndex: 'courseName',
        },
        {
            title: '课程简介',
            dataIndex: 'courseContent',
        },
        {
            title: '课程开始时间',
            dataIndex: 'startTime',
        },
        {
            title: '课程结束时间',
            dataIndex: 'endTime',
        },
        {
            title: '操作',
            dataIndex: 'isFinished',
            render: (_: any, record: any) => {
                return <>
                    <Tag color={'blue'} onClick={() => { getStudentLists(record) }} className={styles.classTag}>学生列表</Tag>
                    <Tag color={'blue'} onClick={() => { changeCourseList(record) }} className={styles.classTag}>修改课程</Tag>
                    <Tag color={'red'} onClick={() => { deleteCourseList(record) }} className={styles.classTag}>删除课程</Tag>
                </>
            }
        },
    ]

    const studentListcolumns = [
        {
            title: '年级',
            dataIndex: 'year',
        },
        {
            title: '班级',
            dataIndex: 'specialty',
        },
        {
            title: '名字',
            dataIndex: 'studentName',
        },
        {
            title: '学号',
            dataIndex: 'studentCode',
        },
        {
            title: '年龄',
            dataIndex: 'age',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            render: (_: any, record: any) => {
                if (record.sex == 1) {
                    return '女'
                } else {
                    return '男'
                }
            }
        },
        {
            title: '邮箱',
            dataIndex: 'email',
        },
        {
            title: '操作',
            dataIndex: 'isFinished',
            render: (_: any, record: any) => {
                return <>
                    <Tag color={'red'} onClick={() => {
                        deleteStudentLists(record.studentId)
                    }} className={styles.classTag}>删除学生</Tag>
                </>
            }
        },
    ]

    const yearListcolumns = [
        {
            title: '年级',
            dataIndex: 'year',
        },
        {
            title: '班级',
            dataIndex: 'specialty',
        },
        {
            title: '名字',
            dataIndex: 'studentName',
        },
        {
            title: '学号',
            dataIndex: 'studentCode',
        },
        {
            title: '年龄',
            dataIndex: 'age',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            render: (_: any, record: any) => {
                if (record.sex == 1) {
                    return '女'
                } else {
                    return '男'
                }
            }
        },
        {
            title: '邮箱',
            dataIndex: 'email',
        },
        {
            title: '操作',
            dataIndex: 'isFinished',
            render: (_: any, record: any) => {
                return <>
                    <Tag color={'blue'} onClick={() => {
                        addYearLists(record.studentId)
                    }} className={styles.classTag}>添加</Tag>
                </>
            }
        },
    ]

    // 获取年级学生列表
    const handleYearChange = async () => {
        const year = await yearForm.validateFields();
        const res = await getYearStudent(year.year)
        setYearList(res.data)
    }

    const onCancel = () => {
        setVisible(false)
    }

    // 添加测验
    const handleAddTestOk = async () => {
        const add = await addTestForm.validateFields();
        const obj = {
            ...add,
            startTime: startTestTime,
            endTime: endTestTime,
            courseId: courseId,
            teacherId: teacherId,
            testId: testId,
            durationTime: startTestTime
        }
        const res = await addTests(qs.stringify(obj))
        if (res.code === 200) {
            message.success('添加成功')
            setAddTestVisvible(false)
            // 刷新表格 注意不要出错
            const ress = await getTeacherTest(courseId)
            setTableData({
                ...tableData,
                [courseId]: ress.data
            })
        }
    }

    const handleAddTestCancel = () => {
        setAddTestVisvible(false)
    }

    // 添加问题
    const handleAddQuestion = () => {
        setAddQuestionVisvible(true)
        const d1: any = localStorage.getItem('1')
        const q1: any = JSON.parse(d1)
        const d2: any = localStorage.getItem('2')
        const q2: any = JSON.parse(d2)
        const d3: any = localStorage.getItem('3')
        const q3: any = JSON.parse(d3)
        const d4: any = localStorage.getItem('4')
        const q4: any = JSON.parse(d4)
        setQ1(q1)
        setQ2(q2)
        setQ3(q3)
        setQ4(q4)
    }

    const renderFooter = () => {
        return (
            <div style={{ textAlign: 'right' }}>
                <Button
                    style={{ marginRight: 8 }}
                    type="primary"
                    // loading={saveLoading}
                    onClick={handleAddQuestion}
                // disabled={disabled}
                >
                    添加问题
              </Button>
            </div>
        );
    }

    const handleAddQuestionOk = async () => {
        const arr: any = [];
        Object.values(questionAddIds).map((item: any) => {
            let len = item.length;
            for (let i = 0; i < len; i++) {
                arr.push(item[i])
            }
        })
        console.log(arr, 'arr');
        arr.forEach(async (item: any, index: number) => {
            const obj = {
                testId: testId,
                questionIds: item
            }
            const res = await addTestQuestions(qs.stringify(obj))
            console.log(res, 'resres');
            if (index === arr.length - 1 && res.code === 200) {
                message.success('添加成功')
                setAddQuestionVisvible(false)
                setVisible(false)
            }
        })
        console.log(drawerRef, 'drawerRef');

        // const res = await addTestQuestions(encodeURI(qs.stringify(obj)))
        // console.log(res, 'resrseers');
        // if (res.code === 200) {
        //     const ress = await getAnswerTest(testId);
        //     if (ress.code === 200) {
        //         setQuestions(res.data)
        //     }
        // }
    }

    const handleAddQuestionCancel = () => {
        setAddQuestionVisvible(false)
    }

    const handleAddQChange1 = (val: any) => {
        const ids = {
            ...questionAddIds,
            1: val
        }
        setQuestionAddIds(ids)
    }

    const handleAddQChange2 = (val: any) => {
        const ids = {
            ...questionAddIds,
            2: val
        }
        setQuestionAddIds(ids)
    }

    const handleAddQChange3 = (val: any) => {
        const ids = {
            ...questionAddIds,
            3: val
        }
        setQuestionAddIds(ids)
    }

    const handleAddQChange4 = (val: any) => {
        const ids = {
            ...questionAddIds,
            4: val
        }
        setQuestionAddIds(ids)
    }

    const studentScorecolumns = [
        {
            title: '姓名',
            dataIndex: 'studentName',
        },
        {
            title: '学号',
            dataIndex: 'studentCode',
        },
        {
            title: '成绩',
            dataIndex: 'scoreValue',
        },
    ]

    const handlestudentScoreCancel = () => {
        setStudentScoreVisvible(false)
    }

    return (
        <>
            <MPageContainer>
                <Card className={styles.card}>
                    <ProTable
                        headerTitle={<div className={styles.tag}><Tag color={'blue'}>课程信息</Tag></div>}
                        columns={columns}
                        dataSource={courseInfo}
                        search={false}
                        rowKey="courseId"
                        pagination={{
                            showQuickJumper: true,
                        }}
                        expandable={{ expandedRowRender, onExpand }}
                        toolBarRender={() => [
                            <Button key="button" icon={<PlusOutlined />} type="primary" onClick={addCourseList}>
                                新建课程
                            </Button>
                        ]}
                    />
                </Card>
            </MPageContainer>
            {
                <Modal title="学生列表" visible={studentListVisvible} onOk={handlestudentListCancel}
                    onCancel={handlestudentListCancel} width={'60%'}>
                    <ProTable
                        headerTitle={<div className={styles.tag}><Tag color={'blue'}>学生列表</Tag></div>}
                        columns={studentListcolumns}
                        dataSource={studentList}
                        search={false}
                        rowKey="studentId"
                        pagination={{
                            showQuickJumper: true,
                        }}
                        // expandable={{ expandedRowRender, onExpand }}
                        toolBarRender={() => [
                            <Button key="button" icon={<PlusOutlined />} type="primary" onClick={addStudentLists}>
                                添加学生
                            </Button>
                        ]}
                    />
                </Modal>
            }
            {
                <Modal title="添加学生" visible={addVisvible} onOk={handleAddStudentCancel} onCancel={handleAddStudentCancel} width={'60%'}>
                    <Form
                        // {...formLayout}
                        form={yearForm}
                    >
                        <Item name="year" rules={[{ required: true }]} label="年级">
                            <Select style={{ width: 120 }} onChange={handleYearChange}>
                                <Option value="2017">2017</Option>
                                <Option value="2018">2018</Option>
                                <Option value="2019">2019</Option>
                            </Select>
                        </Item>
                    </Form>
                    <ProTable
                        headerTitle={<div className={styles.tag}><Tag color={'blue'}>年级学生列表</Tag></div>}
                        columns={yearListcolumns}
                        dataSource={yearList}
                        search={false}
                        rowKey="studentId"
                        pagination={{
                            showQuickJumper: true,
                        }}
                        // expandable={{ expandedRowRender, onExpand }}
                        toolBarRender={() => [
                            // <Button key="button" icon={<PlusOutlined />} type="primary" onClick={addStudentLists}>
                            //     添加学生
                            // </Button>
                        ]}
                    />
                </Modal>
            }
            {
                <Modal title={add ? '新建课程' : '修改课程'} visible={changeCourseVisvible} onOk={handleChangeCourseOk} onCancel={handleChangeCourseCancel}>
                    <Form
                        {...formLayout}
                        form={changeCourseForm}
                    >
                        <Item name="courseName" rules={[{ required: true }]} label="课程名称">
                            <Input size="large" placeholder="请输入课程名称" />
                        </Item>
                        <Item name="courseContent" rules={[{ required: true }]} label="课程简介">
                            <Input size="large" placeholder="请输入课程简介" />
                        </Item>
                        <Item name="startTime" rules={[{ required: true }]} label="开始时间">
                            <DatePicker showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} format="YYYY-MM-DD HH:mm:ss"
                                onChange={(fieldValue, value) => {
                                    setStartTime(value)
                                }}
                            />
                        </Item>
                        <Item name="endTime" rules={[{ required: true }]} label="结束时间">
                            <DatePicker showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} format="YYYY-MM-DD HH:mm:ss"
                                onChange={(fieldValue, value) => {
                                    setEndTime(value)
                                }}
                            />
                        </Item>
                    </Form>
                </Modal>
            }
            <Drawer
                title={testType == 1 ? '测验' : '考试'}
                visible={visible}
                onClose={onCancel}
                width="100%"
                bodyStyle={{
                    background: '#f0f0f0'
                }}
                footer={renderFooter()}
                className={styles.main}>
                {
                    questions?.map((item: any, index: number) => {
                        if (item.type === 1) {
                            return <Program
                                data={item}
                                idx={index}
                                testId={testId}
                            />
                        }
                        else if (item.type === 2) {
                            return <Judge
                                data={item}
                                idx={index}
                                testId={testId}
                            />
                        } else if (item.type === 3) {
                            return <Choice
                                data={item}
                                idx={index}
                                testId={testId}
                            />
                        } else if (item.type === 4) {
                            return <Blanks
                                data={item}
                                idx={index}
                                testId={testId}
                            />
                        }
                        return ''
                    })
                }
            </Drawer>
            {
                <Modal title={'新建测验'} visible={addTestVisvible} onOk={handleAddTestOk} onCancel={handleAddTestCancel}>
                    <Form
                        {...formLayout}
                        form={addTestForm}
                    >
                        <Item name="testName" rules={[{ required: true }]} label="测验名称">
                            <Input size="large" placeholder="请输入测验名称" />
                        </Item>
                        <Item name="type" rules={[{ required: true }]} label="测验类型">
                            <Select style={{ width: 120 }}>
                                <Option value="1">测验</Option>
                                <Option value="2">考试</Option>
                            </Select>
                        </Item>
                        <Item name="startTime" rules={[{ required: true }]} label="开始时间">
                            <DatePicker showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} format="YYYY-MM-DD HH:mm:ss"
                                onChange={(fieldValue, value) => {
                                    setTestStartTime(value)
                                }}
                            />
                        </Item>
                        <Item name="endTime" rules={[{ required: true }]} label="结束时间">
                            <DatePicker showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} format="YYYY-MM-DD HH:mm:ss"
                                onChange={(fieldValue, value) => {
                                    setTestEndTime(value)
                                }}
                            />
                        </Item>
                    </Form>
                </Modal>
            }
            {
                <Modal title={'添加问题'} visible={addQuestionVisvible} onOk={handleAddQuestionOk} onCancel={handleAddQuestionCancel}>
                    <Form
                        {...formLayout}
                    >
                        <Item name="编程题" label="编程题">
                            <Select
                                mode="multiple"
                                style={{ width: '100%' }}
                                placeholder="请选择编程题"
                                onChange={handleAddQChange1}
                            // optionLabelProp="label"
                            >{
                                    q1?.map((item: any) => {
                                        return <Option value={item.questionId} label={item.title}>
                                            <div >
                                                {item.title}
                                            </div>
                                        </Option>
                                    })
                                }
                            </Select>
                        </Item>
                        <Item name="判断题" label="判断题">
                            <Select
                                mode="multiple"
                                style={{ width: '100%' }}
                                placeholder="请选择判断题"
                                onChange={handleAddQChange2}
                            // optionLabelProp="label"
                            >{
                                    q2?.map((item: any) => {
                                        return <Option value={item.questionId} label={item.title}>
                                            <div >
                                                {item.title}
                                            </div>
                                        </Option>
                                    })
                                }
                            </Select>
                        </Item>
                        <Item name="选择题" label="选择题">
                            <Select
                                mode="multiple"
                                style={{ width: '100%' }}
                                placeholder="请选择选择题"
                                onChange={handleAddQChange3}
                            // optionLabelProp="label"
                            >{
                                    q3?.map((item: any) => {
                                        return <Option value={item.questionId} label={item.title}>
                                            <div >
                                                {item.title}
                                            </div>
                                        </Option>
                                    })
                                }
                            </Select>
                        </Item>
                        <Item name="填空题" label="填空题">
                            <Select
                                mode="multiple"
                                style={{ width: '100%' }}
                                placeholder="请选择填空题"
                                onChange={handleAddQChange4}
                            // optionLabelProp="label"
                            >{
                                    q4?.map((item: any) => {
                                        return <Option value={item.questionId} label={item.title}>
                                            <div >
                                                {item.title}
                                            </div>
                                        </Option>
                                    })
                                }
                            </Select>
                        </Item>
                    </Form>
                </Modal>
            }
            {
                <Modal title="学生成绩" visible={studentScoreVisvible} onOk={handlestudentScoreCancel}
                    onCancel={handlestudentScoreCancel} width={'60%'}>
                    <ProTable
                        headerTitle={<div className={styles.tag}><Tag color={'blue'}>学生成绩</Tag></div>}
                        columns={studentScorecolumns}
                        dataSource={studentScoreList}
                        search={false}
                        rowKey="studentId"
                        pagination={{
                            showQuickJumper: true,
                        }}
                    />
                </Modal>
            }
        </>
    );
}

export default Center;
